// 渲染出用户
var html;
var htmls;
var receive_ids = "";
var videoNums = 0;
(function render() {
    // htmls = Math.floor(Math.random() * 10000)
    htmls = 10000//房间号
    html = localStorage.getItem("user_id");//用户id



    $.getJSON(apiUrl.baseURL + apiUrl.meetingList,
        {
            token: localStorage.getItem("token"),
        },
        function (json) {
            // console.log(json.data.items)
            var roomdom = ""
            if (json.data.items.lenght == 0) {
                history.go(-1)
            }
            json.data.items.forEach((v, i) => {
                // console.log(v, i)
                roomdom += `<div class="model" room_id=${v.room_id}>${v.title}</div>`
            });
            $(".content_left_box").html(roomdom)
            $(".model").eq(0).addClass("active")
            $(".model").bind("click", function (e) {
                $(".model").removeClass("active");
                e.target.className = "model active";
                // console.log(e.target.attributes[1].value)
                quitRTC();
                push(e.target.attributes[1].value)
            });
            push($(".model").eq(0).attr("room_id"))
        });
})();



function push(areaid) {

    $.getJSON(apiUrl.baseURL + apiUrl.getSig,
        {
            deviceId: html,
            token: localStorage.getItem("token"),
        },
        function (json) {
        }).then(json => {
            var tmpObj = json.data;
            // console.log(tmpObj)
            var userSig = tmpObj.sig;
            // 页面处理，显示视频流页面
            receive_ids = areaid;
            initRTC({
                "roomid": areaid,
                "userId": html,
                "userSig": userSig,
                "sdkappid": tmpObj.sdkappid,
                "accountType": 1, // 随便传一个值，现在没有啥用处
            });
        });
}

function onKickout() {
    alert("on kick out!");
}

function quitRTC() {
    RTC.quit();
    $(".video_box").html("<div class=titles>等待加入沟通平台.....</div>")
    $(".uesr_box").html("");
    //在线人数清空
    videoNums = 0;
    $("#onlinenum").text(0);

}

function onRelayTimeout(msg) {
    alert("onRelayTimeout!" + (msg ? JSON.stringify(msg) : ""));
}

function createVideoElement(id, isLocal) {
    //	debugger
    var videoDiv = '<video id="' + id + '" autoplay ' + (isLocal ? 'muted' : '') + ' playsinline class=videos ></video>';
    $(".video_box").html(videoDiv);

    //  alert(receive_ids)
    //在线人数清空
    videoNums = 0;
    $("#onlinenum").text(0);
    return document.getElementById(id);

}

function addVideoElement(id, isLocal, name) { //创捷视频dom
    //	debugger
    var videoDiv = '<div class=suer_model><video id="' + id + '" autoplay ' + (isLocal ? 'muted' : '') + ' playsinline class=videos ></video><div class=video_name>' + name + '</div></div>';
    $(".uesr_box").append(videoDiv);
    //在线人数
    videoNums++;
    $("#onlinenum").text(videoNums);
    //  alert(receive_ids)
    $(".suer_model").bind("click", function (e) {
        event.stopPropagation()
        event.preventDefault()
        // console.log(e)
        $(".suer_model").removeClass("outdom")
        e.currentTarget.className = "suer_model outdom"
    });
    return document.getElementById(id);

}

function onLocalStreamAdd(info) {
    // console.log("本地流新增")
    if (info.stream && info.stream.active === true) {
        var id = "local";
        var video = document.getElementById(id);
        if (!video) {
            addVideoElement(id, true, localStorage.getItem("name"));
        }
        var video = document.getElementById(id)
        video.srcObject = info.stream;
        video.muted = true
        video.autoplay = true
        video.playsinline = true
    }
    $(".video_box").html("")

    $(".suer_model").eq(0).addClass("outdom")

}

function onRemoteStreamUpdate(info) {
    // console.log(info, "远端流新增")




    if (info.stream && info.stream.active === true) {
        var id = info.videoId;
        var video = document.getElementById(id);
        if (!video) {
            video = addVideoElement(id);
        }
        video.srcObject = info.stream;
    } else {
        // console.log('欢迎用户' + info.userId + '加入房间');
    }


    if (info.stream && info.stream.active === true) {
        var id = info.videoId;
        var video = document.getElementById(id);
        var userids = info.userId
        // debugger
        if (info.type == 'video') {
            $.getJSON(apiUrl.baseURL + apiUrl.meetingname,
                {
                    deviceIds: info.userId,
                    token: localStorage.getItem("token"),
                },
                function (json) {
                    // console.log(json)
                }).then(json => {
                    if (document.getElementById(id)) {
                        // video = addVideoElement(id, true, );
                        document.getElementById(id).parentNode.children[1].innerText = json.data[userids]
                    }
                    video.srcObject = info.stream;

                });
        }
    } else {
        // console.log('欢迎用户' + info.userId + '加入房间');
    }
}

function onRemoteStreamRemove(info) {
    // console.log(info.userId + ' 断开了连接');
    var videoNode = document.getElementById(info.videoId);
    if (videoNode) {
        //      videoNode.srcObject = null;
        document.getElementById(info.videoId).parentElement.remove();
        //在线人数
        videoNums--;
        $("#onlinenum").text(videoNums);
    }
    // console.log("有人离开房间了")
}

function onWebSocketClose() {
    RTC.quit();
}

function gotStream(opt, succ) {
    // debugger
    // console.log(RTC,9999999999999999999999999999999)
    RTC.getLocalStream({
        video: true,
        audio: true,
        videoDevice: opt.videoDevice,
        // 如需指定分辨率，可以在attributes中增加对width和height的约束
        // 否则将获取摄像头的默认分辨率
        // 更多配置项 请参考 接口API
        // https://cloud.tencent.com/document/product/647/17251#webrtcapi.getlocalstream
        // attributes: {
        //     width: 1280,
        //     height: 720
        // }
    }, function (info) {
        var stream = info.stream;
        succ(stream)
    });
}

function initRTC(opts, areaid) {
    window.RTC = new WebRTCAPI({
        userId: opts.userId,
        userSig: opts.userSig,
        sdkAppId: opts.sdkappid,
        accountType: opts.accountType
    }, function () {
        RTC.enterRoom({
            roomid: opts.roomid * 1,
            privateMapKey: opts.privateMapKey,
            role: "user",
        }, function (info) {
            // console.warn("init succ", info)
            gotStream({
                audio: true,
                video: true
            }, function (stream) {
                RTC.startRTC({
                    stream: stream,
                    role: 'user'
                });
            })
        }, function (error) {
            // console.error("init error", error)
        });
    }, function (error) {
        // console.warn("init error", error)
    });

    // 远端流新增/更新
    RTC.on("onRemoteStreamUpdate", onRemoteStreamUpdate)
    // 本地流新增
    RTC.on("onLocalStreamAdd", onLocalStreamAdd)
    // 远端流断开
    RTC.on("onRemoteStreamRemove", onRemoteStreamRemove)
    // 重复登录被T
    RTC.on("onKickout", onKickout)
    // 服务器超时
    RTC.on("onRelayTimeout", onRelayTimeout)

    RTC.on("onErrorNotify", function (info) {

        if (info.errorCode === RTC.getErrorCode().GET_LOCAL_CANDIDATE_FAILED) {
            // alert( info.errorMsg )
        }
    });
    RTC.on("onStreamNotify", function (info) {

        // console.warn('onStreamNotify', info)
    });
    RTC.on("onWebSocketNotify", function (info) {

        // console.warn('onWebSocketNotify', info)
    });
    RTC.on("onUserDefinedWebRTCEventNotice", function (info) {

        // console.error( 'onUserDefinedWebRTCEventNotice',info )
    });
}



function audience() {
    login(true);
}

function stopRTC() {
    RTC.stopRTC(0, function (info) {
        // console.debug(info)
    }, function (info) {
        // console.debug(info)
    });
}

function stopWs() {
    RTC.global.websocket.close();
}

function startRTC() {
    RTC.startRTC(0, function (info) {

        // console.debug('success', info)
    }, function (info) {
        // console.debug('failed', info)
    });
}

function findUserToken(userid) {
    return genTestUserSig(userid);
}